package com.asj.house.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.asj.house.entity.HouseHits;
import com.asj.house.entity.HouseRoom;
import com.asj.house.mapper.HouseHitsMapper;
import com.asj.house.returns.RespCode;
import com.asj.house.returns.RespEntity;
import com.asj.house.service.HouseHitsService;
import com.asj.house.service.HouseRoomService;
import com.asj.house.vo.AxisVO;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 房屋点击量表 服务实现类
 * </p>
 *
 * @author asj
 * @since 2021-03-16
 */
@Service
public class HouseHitsServiceImpl extends ServiceImpl<HouseHitsMapper, HouseHits> implements HouseHitsService {

    @Autowired
    private HouseRoomService houseRoomService;

    @Override
    public RespEntity<AxisVO> houseHits() {
        QueryWrapper<HouseHits> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(HouseHits::getDeleted, 0);
        List<HouseHits> houseHitsList = baseMapper.selectList(queryWrapper);

        if (Objects.isNull(houseHitsList) || CollectionUtil.isEmpty(houseHitsList)) {
            return new RespEntity<>(RespCode.SUCCESS);
        }

        //按照点击量降序排序
        houseHitsList = houseHitsList.stream()
                .sorted(Comparator.comparing(HouseHits::getHits).reversed())
                .limit(10)
                .collect(Collectors.toList());

        //X轴数据组装
        List<String> xAxis = Lists.newArrayList();
        for (HouseHits houseHits : houseHitsList) {
            HouseRoom houseRoom = houseRoomService.getById(houseHits.getRoomId());
            xAxis.add(houseRoom.getName());
        }

        //Y轴数据组装
        List<String> yAxis = houseHitsList.stream()
                .map(v -> String.valueOf(v.getHits()))
                .collect(Collectors.toList());

        return new RespEntity<>(RespCode.SUCCESS, new AxisVO(xAxis, yAxis));
    }
}
